// pages/audioDetail/audioDetail.js
let WxParse = require('../../wxParse/wxParse.js');
let util = require("../../utils/util.js");
const jumpurl = util.jumpurl;
var baseImgUrl = util.baseImgUrl;
let app = getApp();

let qrCodePath;
let goodsPicPath;
var imageWidth;//画布宽度
var imageHeight;
var scaleRate;//缩放比newsSrc
var imageTop;
let logoUrl = util.imgUrl + "jktc_logo.png";
var newsSrc = "";
let access_token;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: baseImgUrl,
    audioshow: false,//视屏是否显示，false--视频隐藏，截图显示  true--反之
    // newsSrc: "http://ones.cakeyouxuan.com/public/white_bg.png",
    greyshow: false,//是否显示分享的图片弹出框，默认为隐藏
    menushow: false,//是否显示分享选择框.默认为隐藏

    follow: 0,
    scanPic:baseImgUrl+"scan_home.png",
    shouyePic:baseImgUrl+"home.png",
    gohome_act:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;

    //获取新闻的id
    var newid;
    if (options.newid) {
      newid = options.newid;
      that.setData({
        newid: options.newid
      })
    } else {
      newid = 0;
    }

    wx.request({
      url: jumpurl + 'index/video_info',
      data: {
        newid: newid,
        openid: app.globalData.openid,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log("**************res*************");
        console.log(res);
        //回填变量
        that.data.newid = res.data.newsId;
        that.data.newstitle = res.data.newstitle;

        var article = res.data.jianjie;
        WxParse.wxParse('article', 'html', article, that, 5);
       
        that.setData({
          articleF: res.data.articleF,
          newsId: res.data.newsId,
          newstitle: res.data.newstitle,
          poster: res.data.poster,
          saveFlag: res.data.saveFlag,
          newestlist: res.data.newestlist,
        });
      },
    }) 

    
    //先展示视频封面，1秒后自动播放视频
    setTimeout(function () {
      that.setData({
        audioshow: true
      }) 
      var myvideo = wx.createVideoContext("myVideo", myvideo);
      myvideo.play();
    }, 0)
  },

  /**********点击推荐视频********/
  audiodetail: function (e) {
    var that = this;
    var newid = e.currentTarget.dataset.id;
    var index_now = e.currentTarget.dataset.index;
    that.data.newestlist[index_now].hasread = 1;
    that.setData({
      newestlist: that.data.newestlist
    })
    wx.navigateTo({
      url: '/pages/audioDetail/audioDetail?newid=' + newid,
    })

  },

  //跳转到首页
  gohome:function(){
    var that=this;
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  //收藏
  shoucang: function (e) {
    var that = this;
    //请求后台，修改收藏值
    var newid = that.data.newid;
   
    //访问接口
    wx.request({
      url: jumpurl+'index/shoucang',
      data: {
        openid: app.globalData.openid,
        newid: newid,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        that.setData({
          saveFlag: res.data.saveFlag,
        })
      },
      fail: function (err) {
        console.log("err" + err);
      }
    })
    
  },

  //取消收藏
  quxiaoshoucang: function (e) {
    var that = this;
    var newid = that.data.newid;
    wx.showModal({
      title: '',
      content: '确定取消收藏',
      cancelColor:"#666",
      cancelText:"取消",
      confirmColor:"#21aaff",
      confirmText:"确定",
      success:function(res){
        if(res.cancel){
           console.log("操作取消")

        }
        if(res.confirm){
          //访问接口
          wx.request({
            url: jumpurl + 'index/shoucang',
            data: {
              openid: app.globalData.openid,
              newid: newid,
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              that.setData({
                saveFlag: res.data.saveFlag,
              })
            },
            fail: function (err) {
              console.log("err" + err);
            }
          })
        }
       
      }
    })
   
    

    
    
  },


  //分享给朋友
  shareFriend: function () {
    wx.showShareMenu({
      withShareTicket: true
    })
  },

  //关闭分享图弹框
  shutgrey: function () {
    var that = this;
    that.setData({
      greyshow: false
    })
  },

  //显示分享选择菜单
  showchosemenu: function () {
    var that = this;
    that.setData({
      menushow: true
    })
  },
  //显示分享选择菜单
  hidechosemunu: function () {
    var that = this;
    that.setData({
      menushow: false
    })
  },

  /********点击分享朋友圈 生成图片*************/
  formSubmit: function (e) {
    var that = this;
    this.setData({
      menushow: false,

    });
    wx.showToast({
      title: '正在生成海报...',
      icon: 'loading',
      duration: 1000
    });
    setTimeout(function () {
      wx.hideToast()
      that.createNewImg();
      that.setData({
        greyshow: true
      });
    }, 2000)
  },

  //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#fff")
    //绘制画布
    context.fillRect(0, 0, 690, 750)
    /***********上部图片路径********************/
    // var path = that.data.picurl;//分享图背景图
    var path="/pages/images/moren_bg.jpg";//测试路径
    //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    //不知道是什么原因，手机环境能正常显示
    //绘制上部图片
    context.drawImage(path, 0, 0, 375, 420);



    //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    var path2="/pages/images/avatar.png"//测试，用户头像
    // var path2 = that.data.avatar;//作者的头像图
    
    // var path3 = logoUrl;//即客同城logo图
    var path4 = "/pages/mine/images/wenziBg.jpg";//二维码图片
    var path5 = "images/friendsPic.png";//分享朋友圈图片
    var pathline = "/pages/images/shortline.png";//直线
    // var nickname = that.data.authorName;
    var nickname="用户名用户名用户名"//测试数据
    //绘制logo
    // context.drawImage(path3, 210, 150, 150, 40);
    //不知道是什么原因，手机环境能正常显示
    // context.save(); // 保存当前context的状态

    //绘制名字
    context.setFontSize(26);
    context.setFillStyle('#333333');
    context.setTextAlign('left');
    /**********文章标题********/
    // var newstitle = that.data.newstitle;
    var newstitle ="ceshicheshishujuceshiceshi测试数据ceshicheshishujuceshiceshi测试数据ceshicheshishujuceshiceshi测试数据"
    /**********换行**开始*******/
    var chr = newstitle.split("");//这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < 345) {
        temp += chr[a];
      }
      else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 330) {
          test += rowPart[a];
        }
        else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..."//这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], 15, 460 + b * 40, 345);

    }



    context.stroke();
    //绘制直线
    context.drawImage(pathline, 15, 520, 345, 1, 82);
    context.setFillStyle('#efefef');
    context.stroke();

    //绘制左下角二维码
    // // context.drawImage(path4, 15, 530, 100, 120);
    // context.setFillStyle('#efefef');
    // context.stroke();


    //绘制右下角上侧logo图
    // context.drawImage(path2, 130, 540, 50, 50, 50, 50);
    // context.setFillStyle('#efefef');
    // context.stroke();

    //绘制右下角上侧文字
    // context.setFontSize(14);
    // context.setFillStyle('#333');
    // context.setTextAlign('left');


    /**********用户名**开始*******/

    nickname = nickname.split("");//这个方法是将一个字符串分割成字符串数组
    var temp2 = "";
    var row2 = [];

    for (var a = 0; a < nickname.length; a++) {
      if (context.measureText(temp2).width < 70) {
        temp2 += nickname[a];
      }
      else {
        a--; //这里添加了a-- 是为了防止字符丢失
        row2.push(temp2);
        temp2 = "";
      }
    }
    row2.push(temp2);
    console.log("row2" + row2);

    //如果数组长度大于1 则截取第1个
    if (row2.length > 1) {
      var rowCut2 = row2.slice(0, 1);//第一条需要截取的字符
      console.log(rowCut2);
      var rowPart2 = rowCut2[0];
      console.log("rowPart2" + rowPart2)
      var test2 = "";
      var empty2 = [];
      for (var a = 0; a < rowPart2.length; a++) {
        if (context.measureText(test2).width < 60) {
          test2 += rowPart2[a];
        }
        else {
          break;
        }
      }
      empty2.push(test2);
      console.log(empty2);
      var group2 = empty2[0] + "..."//

      rowCut2.splice(0, 1, group2);
      context.fillText(rowCut2[0], 190, 570, 70);
    }


    context.stroke();


    /*****************************************/
    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("正在浏览文章", 270, 570, 164);
    context.stroke();

    //绘制右下角下侧文字
    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("识别小程序，进入", 130, 630);
    context.stroke();

    context.setFontSize(14);
    context.setFillStyle('#ff1313');
    context.setTextAlign('left');
    context.fillText("优当课堂", 240, 630);
    context.stroke();

    context.setFontSize(14);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText("观看视频", 300, 630);
    context.stroke();
    console.log("----------context------------")
    console.log(context);
    context.draw();
    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function () {
      wx.canvasToTempFilePath({
        x: 0,
        y: 133,
        width: 690,
        height: 750,
        destHeight: 750,
        destWidth: 690,
        canvasId: 'mycanvas',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true
          });
          that.baocun();
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 200);
  },

  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        console.log("图片保存成功")
        // wx.showModal({
        //   content: '图片已保存到相册，赶紧晒一下吧~',
        //   showCancel: false,
        //   confirmText: '好的',
        //   confirmColor: '#333',
        //   success: function (res) {
        //     if (res.confirm) {
        //       console.log('用户点击确定');
        //       /* 该隐藏的隐藏 */
        //       that.setData({
        //         maskHidden: false
        //       })
        //     }
        //   }, fail: function (res) {
        //     console.log(11111)
        //   }
        // })
      }
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var that = this;
    var openid = app.globalData.openid;
    var jumpurl = util.jumpurl;
    var newid=that.data.newid;
    console.log(newid);
     // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: that.data.newstitle, // 默认是小程序的名称(可以写slogan等)
      desc: "优当课堂",
      path: '/pages/audioDetail/audioDetail?newid='+newid+'&openid=' + openid, // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl: 'http://word.youdang.xin/public/tuzi.jpg',//图片//图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        console.log("转发成功")
      },
      fail: function (res) {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发

          console.log(options.target.dataset.id)

        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }
    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;

      console.log(options);
      //  内容
      shareObj.path = '/pages/audioDetail/audioDetail?newid=' + newid + '&openid=' + openid;

      shareObj.imageUrl = "http://word.youdang.xin/public/tuzi.jpg"

    }
    // 返回shareObj
    return shareObj;
 
  }
})